"""
学生信息管理序列化器
"""
from rest_framework import serializers
from django.contrib.auth import get_user_model
from .models import School, Major, Grade, Student, TeacherStudentAssignment

User = get_user_model()


class SchoolSerializer(serializers.ModelSerializer):
    """校区序列化器"""

    class Meta:
        model = School
        fields = ['id', 'name', 'code', 'principal', 'phone', 'address']


class MajorSerializer(serializers.ModelSerializer):
    """专业序列化器"""

    class Meta:
        model = Major
        fields = ['id', 'name', 'description']


class GradeSerializer(serializers.ModelSerializer):
    """年级序列化器"""

    class Meta:
        model = Grade
        fields = ['id', 'name', 'description']




class TeacherSerializer(serializers.ModelSerializer):
    """老师序列化器（用于下拉选择）"""

    full_name = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ['id', 'username', 'first_name', 'last_name', 'full_name', 'email']

    def get_full_name(self, obj):
        """获取老师全名"""
        if obj.first_name and obj.last_name:
            return f"{obj.first_name} {obj.last_name}"
        return obj.username


class UserInfoSerializer(serializers.ModelSerializer):
    """用户信息序列化器（用于学生账号信息）"""

    class Meta:
        model = User
        fields = ['id', 'username', 'is_active', 'date_joined', 'last_login']


class StudentSerializer(serializers.ModelSerializer):
    """学生序列化器"""

    school_info = SchoolSerializer(source='school', read_only=True)
    major_info = MajorSerializer(source='major', read_only=True)
    grade_info = GradeSerializer(source='grade', read_only=True)
    advisor_info = TeacherSerializer(source='advisor', read_only=True)
    user = UserInfoSerializer(read_only=True)

    class Meta:
        model = Student
        fields = [
            'id', 'student_id', 'name', 'gender', 'birth_date', 'phone', 'email',
            'school', 'school_info', 'major', 'major_info', 'grade', 'grade_info',
            'enrollment_date', 'graduation_date', 'advisor', 'advisor_info', 'user',
            'status', 'employment_status', 'resume_status', 'address', 'notes',
            'created_at', 'updated_at'
        ]
        read_only_fields = ['created_at', 'updated_at']


class StudentCreateSerializer(serializers.ModelSerializer):
    """学生创建序列化器"""

    school_info = SchoolSerializer(source='school', read_only=True)
    major_info = MajorSerializer(source='major', read_only=True)
    grade_info = GradeSerializer(source='grade', read_only=True)
    username = serializers.CharField(write_only=True, required=False, help_text="用户名，如果不提供则使用学号")
    password = serializers.CharField(write_only=True, default='123456', help_text="初始密码，默认为123456")

    class Meta:
        model = Student
        fields = [
            'id', 'student_id', 'name', 'gender', 'birth_date', 'phone', 'email',
            'school', 'school_info', 'major', 'major_info', 'grade', 'grade_info',
            'enrollment_date', 'graduation_date', 'advisor', 'status', 'employment_status',
            'resume_status', 'address', 'notes', 'username', 'password',
            'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'student_id', 'created_at', 'updated_at']

    def validate_student_id(self, value):
        if Student.objects.filter(student_id=value).exists():
            raise serializers.ValidationError("学号已存在")
        return value

    def validate_username(self, value):
        if value and User.objects.filter(username=value).exists():
            raise serializers.ValidationError("用户名已存在")
        return value

    def validate_email(self, value):
        if value and User.objects.filter(email=value).exists():
            raise serializers.ValidationError("邮箱已被使用")
        return value

    def validate_phone(self, value):
        if value and User.objects.filter(phone=value).exists():
            raise serializers.ValidationError("手机号已被使用")
        return value

    def generate_student_id(self):
        """生成学号"""
        import datetime
        import random

        # 获取当前年份
        current_year = datetime.datetime.now().year
        year_suffix = str(current_year)[-2:]  # 取年份后两位

        # 生成随机6位数字
        while True:
            random_num = random.randint(100000, 999999)
            student_id = f"{year_suffix}{random_num}"

            # 检查学号是否已存在
            if not Student.objects.filter(student_id=student_id).exists():
                return student_id

    def create(self, validated_data):
        # 自动生成学号
        if 'student_id' not in validated_data or not validated_data['student_id']:
            validated_data['student_id'] = self.generate_student_id()

        # 提取用户相关数据
        username = validated_data.pop('username', None)
        password = validated_data.pop('password', '123456')

        # 如果没有提供用户名，使用学号作为用户名
        if not username:
            username = validated_data['student_id']

        # 创建用户账号
        user_data = {
            'username': username,
            'password': password,
            'role': 'student',
            'is_active': True,
        }

        # 如果提供了邮箱和手机号，也添加到用户账号
        if validated_data.get('email'):
            user_data['email'] = validated_data['email']
        if validated_data.get('phone'):
            user_data['phone'] = validated_data['phone']

        # 设置用户的姓名
        user_data['first_name'] = validated_data['name']

        # 创建用户
        user = User.objects.create_user(**user_data)

        # 创建学生档案并关联用户
        validated_data['user'] = user
        student = super().create(validated_data)

        return student


class StudentUpdateSerializer(serializers.ModelSerializer):
    """学生更新序列化器"""

    school_info = SchoolSerializer(source='school', read_only=True)
    major_info = MajorSerializer(source='major', read_only=True)
    grade_info = GradeSerializer(source='grade', read_only=True)

    class Meta:
        model = Student
        fields = [
            'id', 'student_id', 'name', 'gender', 'birth_date', 'phone', 'email',
            'school', 'school_info', 'major', 'major_info', 'grade', 'grade_info',
            'enrollment_date', 'graduation_date', 'advisor', 'status', 'employment_status',
            'resume_status', 'address', 'notes', 'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'student_id', 'created_at', 'updated_at']


class StudentBatchCreateSerializer(serializers.Serializer):
    """学生批量创建序列化器"""
    
    students = serializers.ListField(
        child=StudentCreateSerializer(),
        min_length=1,
        max_length=100
    )
    
    def create(self, validated_data):
        students_data = validated_data['students']
        created_students = []
        errors = []
        
        for i, student_data in enumerate(students_data):
            try:
                serializer = StudentCreateSerializer(data=student_data)
                if serializer.is_valid():
                    student = serializer.save()
                    created_students.append(student)
                else:
                    errors.append({
                        'index': i,
                        'student_id': student_data.get('student_id'),
                        'errors': serializer.errors
                    })
            except Exception as e:
                errors.append({
                    'index': i,
                    'student_id': student_data.get('student_id'),
                    'errors': str(e)
                })
        
        return {
            'created_students': created_students,
            'errors': errors,
            'success_count': len(created_students),
            'error_count': len(errors)
        }


class TeacherStudentAssignmentSerializer(serializers.ModelSerializer):
    """师生分配关系序列化器"""
    
    teacher_info = serializers.SerializerMethodField()
    student_info = serializers.SerializerMethodField()
    
    class Meta:
        model = TeacherStudentAssignment
        fields = '__all__'
        read_only_fields = ['assigned_date']
    
    def get_teacher_info(self, obj):
        return {
            'id': obj.teacher.id,
            'username': obj.teacher.username,
            'first_name': obj.teacher.first_name,
            'last_name': obj.teacher.last_name,
        }
    
    def get_student_info(self, obj):
        return {
            'id': obj.student.id,
            'student_id': obj.student.student_id,
            'name': obj.student.name,
            'class_name': obj.student.full_class_name,
        }


class StudentStatisticsSerializer(serializers.Serializer):
    """学生统计序列化器"""
    
    total_students = serializers.IntegerField()
    active_students = serializers.IntegerField()
    graduated_students = serializers.IntegerField()
    employed_students = serializers.IntegerField()
    employment_rate = serializers.FloatField()
    resume_completed = serializers.IntegerField()
    resume_completion_rate = serializers.FloatField()
    interview_participated = serializers.IntegerField()
    
    by_class = serializers.DictField()
    by_major = serializers.DictField()
    by_employment_status = serializers.DictField()
    by_resume_status = serializers.DictField()


class StudentImportSerializer(serializers.Serializer):
    """学生导入序列化器"""

    file = serializers.FileField()

    def validate_file(self, value):
        if not value.name.endswith(('.xlsx', '.xls', '.csv')):
            raise serializers.ValidationError("只支持Excel文件格式(.xlsx, .xls)或CSV格式(.csv)")

        # 检查文件大小（10MB限制）
        if value.size > 10 * 1024 * 1024:
            raise serializers.ValidationError("文件大小不能超过10MB")

        return value


class StudentBatchImportSerializer(serializers.Serializer):
    """学生批量导入数据序列化器"""

    name = serializers.CharField(max_length=50, help_text="姓名")
    password = serializers.CharField(max_length=128, default='123456', help_text="密码")
    gender = serializers.ChoiceField(choices=[('M', '男'), ('F', '女')], default='M', help_text="性别")
    birth_date = serializers.DateField(required=False, allow_null=True, help_text="出生日期")
    phone = serializers.CharField(max_length=20, help_text="手机号")
    email = serializers.EmailField(help_text="邮箱")
    school_name = serializers.CharField(max_length=100, help_text="校区名称")
    major_name = serializers.CharField(max_length=100, help_text="专业名称")
    grade_name = serializers.CharField(max_length=50, help_text="年级名称")
    enrollment_date = serializers.CharField(max_length=7, required=False, allow_blank=True, help_text="入学日期(YYYY-MM)")
    graduation_date = serializers.CharField(max_length=7, required=False, allow_blank=True, help_text="毕业日期(YYYY-MM)")
    advisor_username = serializers.CharField(max_length=150, required=False, allow_blank=True, help_text="指导老师用户名")
    address = serializers.CharField(required=False, allow_blank=True, help_text="家庭地址")
    notes = serializers.CharField(required=False, allow_blank=True, help_text="备注")

    def validate_phone(self, value):
        """验证手机号格式"""
        import re
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError("手机号格式不正确")
        return value

    def validate_enrollment_date(self, value):
        """验证入学日期格式"""
        if value:
            import re
            if not re.match(r'^\d{4}-\d{2}$', value):
                raise serializers.ValidationError("入学日期格式应为YYYY-MM")
        return value

    def validate_graduation_date(self, value):
        """验证毕业日期格式"""
        if value:
            import re
            if not re.match(r'^\d{4}-\d{2}$', value):
                raise serializers.ValidationError("毕业日期格式应为YYYY-MM")
        return value
